import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import App from 'layout/App.js'
import './index.less';
import { Icon, Table, Pagination, FormControl, Button, Popconfirm, Breadcrumb } from 'tinper-bee';
import { searchCollate, deleteCollate } from './workdataref.config'
import { vendorsDanger as danger, vendorsSuccess as success, vendorsFmtDate as fmtDate, vendorsTrimStr as trimStr } from 'utils/config.js';
import CommonModal from './../../components/CommonModal/index.jsx';
import PresetTemplate from './../../components/PresetTemplate/index.jsx';

import Tooltip from 'bee-tooltip';
import 'bee-tooltip/build/Tooltip.css';
const textOverflowIndex = 10; // 控制项目名称在多少个字符后隐藏

import jdiwork from '../../utils/jdiwork'
let tenantId;
let userId;

export default class WorkDataRef extends Component {
    constructor(props) {
        super(props);

        this.state = {
            docData: [],
            docActivePage: 1,
            docItems: 1,
            docSearchText: ''
        };
    }

    getDocList = (condition, start, size = 10) => {
        let _me = this;

        if (document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)) {
            userId = document.cookie.split(';').find(cur => cur.indexOf('userId=') != -1).split('=')[1];
            tenantId = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1).split('=')[1];
            this.getDocListHelper(condition, start, size, _me);
        } else {
            jdiwork().getContext((data) => {
                tenantId = data.tenantid;
                userId = data.userid;
                this.getDocListHelper(condition, start, size, _me);
            });
        }
    }

    getDocListHelper = (condition, start, size, _me) => {
        searchCollate({ 'isAjax': 1, ieStamp: new Date().getTime(), 'condition': condition, 'start': start, 'size': size, 'pkTenant': tenantId })
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    let data = response.data.result.objects;
                    let pages = Math.ceil(response.data.result.count / 10);

                    data.forEach((cur, index) => {
                        cur.key = cur.pkCompletedCollate;
                        let temp = (index + 1).toString();
                        temp = temp.length < 2 ? 0 + temp : temp;
                        cur.number = temp;
                        cur.creationtime = fmtDate(cur.creationtime);
                    });

                    _me.setState({
                        docData: data,
                        docItems: pages
                    });

                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }

    componentDidMount = () => {
        let _me = this;

        sessionStorage.removeItem('docpagestate');
        sessionStorage.removeItem('projectName');
        sessionStorage.removeItem('pkProject');
        sessionStorage.removeItem('billType');
        sessionStorage.removeItem('procedurePkArr');
        sessionStorage.removeItem('pkCompletedCatalogB');
        sessionStorage.removeItem('editdoc');
        sessionStorage.removeItem('showdoc');
        sessionStorage.removeItem('fromSubmit');


        this.getDocList(this.state.docSearchText, this.state.docActivePage);
    }


    handleSearchClick = (e) => {
        if (e.charCode && e.charCode != 13) return;

        let st = trimStr(this.state.docSearchText);

        this.setState({
            docSearchText: st
        });

        this.getDocList(st, 1);

    }

    handleDocSelect = (e) => {
        this.setState({
            docActivePage: e
        });
        this.getDocList(this.state.docSearchText, e);

    }

    handleDocSearchChange = (e) => {
        this.setState({ docSearchText: e.target.value });
    }

    addCollate = () => {
        sessionStorage.removeItem("editdoc");
        sessionStorage.removeItem("showdoc");
        window.location.href = "./workdatadoc.html";
    }

    editCollate = (record, e) => {
        console.log('编辑行');
        if (record.creator != userId && record.manager != userId) {
            danger({ 'text': '项目经理或资料创建人才有此权限！' });
            return;
        }
        sessionStorage.setItem("editdoc", record.pkCompletedCollate);
        sessionStorage.removeItem("showdoc");
        window.location.href = "./workdatadoc.html";
    }

    showCollate = (record, e) => {
        console.log('查看行');
        sessionStorage.removeItem("editdoc");
        sessionStorage.setItem("showdoc", record.pkCompletedCollate);
        window.location.href = "./workdatadoc.html";
    }

    deleteCollate = (text, record, e) => {
        console.log('删除资料');
        if (record.creator != userId && record.manager != userId) {
            danger({ 'text': '项目经理或资料创建人才有此权限！' });
            return;
        }
        let _me = this;
        let collateVO = this.state.docData.find(cur => cur.pkCompletedCollate == text);
        collateVO.isAjax = 1;
        collateVO.ieStamp = new Date().getTime();

        deleteCollate(collateVO)
            .then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    if (_me.state.docData.length <= 1) {
                        _me.state.docActivePage = (_me.state.docActivePage - 1) || 1;
                    }

                    _me.getDocList(_me.state.docSearchText, _me.state.docActivePage);
                } else {
                    danger({ 'text': response.data.exMsg });
                }
            });
    }


    render() {
        let _me = this;

        const columnsRefCata = [
            { title: "序号", dataIndex: "number", key: "a", width: '4%' },
            {
                title: "资料名称", dataIndex: "sname", key: "b", width: 200,
                render(text, record, index) {
                    return (
                        <div className="hrowop">
                            <span onClick={_me.showCollate.bind(null, record)}>{text}</span>
                        </div>
                    );
                }
            },
            {
                title: "项目名称", dataIndex: "projectName", key: "c", width: 200, render(text, rec, index) {
                    let displayText = text.length > textOverflowIndex ? text.substr(0, textOverflowIndex) + "..." : text;
                    return (
                        <Tooltip
                            className={[text.length > textOverflowIndex ? "show" : "hidden"]}
                            inverse
                            placement="top"
                            overlay={text}>
                            <div>{displayText}</div>
                        </Tooltip>
                    )
                }
            },
            { title: "项目经理", dataIndex: "managerName", key: "d", width: '6%' },
            { title: "目录名称", dataIndex: "catalogName", key: "e", width: 200 },
            { title: "创建人", dataIndex: "creatorName", key: "f", width: '6%' },
            { title: "创建日期", dataIndex: "creationtime", key: "g", width: '7%' },
            {
                title: "操作", dataIndex: "pkCompletedCollate", key: "h",
                render(text, record, index) {

                    return (
                        <div className="hrowop">
                            <span onClick={_me.editCollate.bind(null, record)}>编辑  </span>|
                            <Popconfirm trigger="click" placement="top" content={<div className="table-delete clearfix">
                                <i className="uf uf-exc-c hdelwarning"></i>
                                <span className="hdelspan">你确定删除该资料吗？</span>
                            </div>} onClose={_me.deleteCollate.bind(null, text, record)} rootClose={true}>
                                <span>  删除</span>
                            </Popconfirm>
                        </div>
                    );
                }, width: '7%'
            }
        ];


        return (
            <App>
                <div className="hhead">
                    <Breadcrumb className="hheadcrumb">
                        <Breadcrumb.Item active>
                            资料列表
                                </Breadcrumb.Item>

                    </Breadcrumb>
                </div>
                <div className="hbodydocument">
                    <div className="hbodyopecata">
                        <div className="hbodyopeleft">
                            资料名称：<FormControl value={this.state.docSearchText} className="hsearch" placeholder="请输入资料名称、项目名称" onChange={this.handleDocSearchChange} onKeyPress={this.handleSearchClick} />
                            <div className="hsearchbtn" onClick={this.handleSearchClick}>
                                <Icon type="uf-search-light-2"></Icon>
                            </div>
                        </div>
                        <div className="hbodyoperight">
                            <Button className="hadd" colors="primary" onClick={this.addCollate}>添加资料</Button>
                        </div>
                    </div>
                    <Table columns={columnsRefCata} data={this.state.docData} useFixedHeader={true} emptyText={() => '暂无数据'} />
                    <div>
                        <Pagination style={{ float: 'right', margin: '5px 0' }}
                            first
                            last
                            prev
                            next
                            boundaryLinks
                            items={this.state.docItems}
                            maxButtons={5}
                            activePage={this.state.docActivePage}
                            onSelect={this.handleDocSelect}
                        />
                        <div style={{ height: '35px' }}></div>
                    </div>
                </div>
            </App>
        );
    }
}